package com.shoulder.boot.system.utils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.shoulder.boot.acl.entity.Role;
import com.shoulder.boot.acl.mapper.RoleMapper;
import com.shoulder.boot.system.dto.TenantQueryDTO;
import com.shoulder.boot.system.entity.Tenant;
import com.shoulder.boot.system.vo.TenantVo;
import com.shoulder.core.utils.FuncUtils;
import com.shoulder.core.utils.MapUtils;
import com.shoulder.mybatis.utils.PageUtils;
import lombok.Data;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Data
public class TenantUtils implements PageUtils<Tenant, TenantVo> {
    //(角色id,角色对象)
    private Map<String, Role> roleMap;

    @Override
    public TenantVo toVo(Tenant tenant) {
        TenantVo vo = new TenantVo();
        BeanUtils.copyProperties(tenant, vo);
        vo.setRoleName(MapUtils.get(vo.getRoleId(), roleMap, new Role()).getName());
        vo.setStatusName(tenant.getStatus().equals(Tenant.DISABLE_STATUS) ? "禁用" : "正常");
        return vo;
    }

    public static LambdaQueryWrapper<Tenant> buildQueryWrapper(TenantQueryDTO queryDTO) {
        LambdaQueryWrapper<Tenant> queryWrapper = new LambdaQueryWrapper<Tenant>().orderByDesc(Tenant::getCreateTime);
        queryWrapper.like(!ObjectUtils.isEmpty(queryDTO.getName()), Tenant::getName, queryDTO.getName());
        queryWrapper.like(!ObjectUtils.isEmpty(queryDTO.getAccount()), Tenant::getAccount, queryDTO.getAccount());
        queryWrapper.eq(!ObjectUtils.isEmpty(queryDTO.getRoleId()), Tenant::getRoleId, queryDTO.getRoleId());
        queryWrapper.like(!ObjectUtils.isEmpty(queryDTO.getAddr()), Tenant::getAddr, queryDTO.getAddr());
        queryWrapper.like(!ObjectUtils.isEmpty(queryDTO.getCharger()), Tenant::getCharger, queryDTO.getCharger());
        queryWrapper.like(!ObjectUtils.isEmpty(queryDTO.getPhone()), Tenant::getPhone, queryDTO.getPhone());
        queryWrapper.eq(!ObjectUtils.isEmpty(queryDTO.getStatus()), Tenant::getStatus, queryDTO.getStatus());
        queryWrapper.like(!ObjectUtils.isEmpty(queryDTO.getLink()), Tenant::getLink, queryDTO.getLink());
        return queryWrapper;
    }

    public static TenantUtils buildUtils(List<Tenant> tenants, RoleMapper roleMapper) {
        TenantUtils tw = new TenantUtils();
        List<String> roleIds = FuncUtils.toList(tenants, Tenant::getRoleId);
        if (!CollectionUtils.isEmpty(roleIds) && roleMapper != null) {
            tw.setRoleMap(roleMapper.selectBatchIds(roleIds).stream().collect(Collectors.toMap(Role::getId, Function.identity())));
        }
        return tw;
    }
}
